<template>
  <div class="ask-ai-popup">
    <el-card class="popup-card">
      <div slot="header" class="card-header">
        <h3>问AI弹出框</h3>
      </div>

      <section>
        <el-input v-model="inputText" class="input-field" placeholder="请输入要查询的文本..." type="textarea" :rows="3" />
        <div style="display: flex;justify-content: space-around;">
          <el-button class="query-button" type="primary" @click="handleQueryAi" icon="el-icon-question"
            v-loading="loadoing1"
                     style="margin-bottom: 0px;"
                     size="mini"
          >
            点击开始问AI
          </el-button>

          <!-- 加入笔记按钮 -->
          <el-button class="note-button" type="success" @click="handleAddToNotes" icon="el-icon-document-add"
                     style="margin-bottom: 0px;"
                     size="mini"
            :disabled="!conceptExplanation || loadoing3" v-loading="loadoing3">
            保存为笔记
          </el-button>
        </div>

      </section>


      <!-- 笔记库存的相关笔记 -->
      <div class="result-section" v-loading="loadoing6">
        <h4>笔记库存的相关笔记</h4>
        <el-card v-if="relatedConceptsInNote.length > 0" class="result-card">
          <ul class="related-concepts-list">
            <li v-for="(item, index) in relatedConceptsInNote" :key="index">

              <div>
                <el-popover :title="item?.name"  trigger="click">
                  <div style="max-width: 435px;overflow: auto;max-height: 450px;">
                    <MdShow :value="item?.content" />
                  </div>
                  <div slot="reference" style="color: #66b1ff;cursor:pointer;">
                    {{ index + 1 }}. {{ item?.name }}
                  </div>
                </el-popover>



              </div>
            </li>
          </ul>
        </el-card>
        <div v-else class="empty-result">
          文档库暂时没有这方面的数据
        </div>
      </div>

      <!-- 概念解释区域 -->
      <div class="result-section" v-loading="loadoing1">
        <h4>搜索的文字的概念解释</h4>
        <el-card v-if="conceptExplanation" class="result-card">
          <MdShow :value="conceptExplanation" />
        </el-card>
        <div v-else class="empty-result">
          等待查询结果...
        </div>
      </div>

      <!-- 相关概念区域 -->
      <div class="result-section" v-loading="loadoing2">
        <h4>和这个概念相关的概念5条</h4>
        <el-card v-if="relatedConcepts.length > 0" class="result-card">
          <ul class="related-concepts-list">
            <li v-for="(concept, index) in relatedConcepts" :key="index">
              <MdShow :value="`${ index + 1 }.${ concept }`" />
            </li>
          </ul>
        </el-card>
        <div v-else class="empty-result">
          等待查询结果...
        </div>
      </div>




    </el-card>
  </div>
</template>

<script>
// 引入Element UI组件
import MdShow from '../../components/MdShow.vue';

export default {
  name: 'AskAiPopup',
  components: {
    MdShow
  },
  data() {
    return {
      inputText: '',
      loadoing1: false,
      lioading2: false,
      loadoing3: false,
      loadoing6: false,
      conceptExplanation: '',
      relatedConcepts: [],
      relatedConceptsInNote: []
    };
  },
  mounted() {
    // 从storage获取选中的文本并填充到输入框
    chrome.storage.local.get('selectedText', (result) => {
      if (result.selectedText) {
        this.inputText = result.selectedText;
      }
    });
  },
  methods: {
    /**
     * 处理AI查询按钮点击事件
     */
    async handleQueryAi() {
      if (!this.inputText.trim()) {
        this.$message.warning('请输入要查询的文本');
        return;
      }


      await this.searchRelatedNotes();

      try {
        // 清空之前的结果
        this.conceptExplanation = '';
        this.relatedConcepts = [];

        // 调用后端API获取概念解释
        this.loadoing1 = true
        const explanationResult = await this.callAskAiApi(`请详细解释这个概念：${this.inputText}`);
        this.conceptExplanation = explanationResult.data?.resultContent || '未获取到解释';
        this.loadoing1 = false

        // 调用后端API获取相关概念
        this.loadoing2 = true
        const relatedResult = await this.callAskAiApi(`请列出与"${this.inputText}"相关的5个概念，每个概念用数字编号，格式如：1. 概念名称`);
        this.relatedConcepts = relatedResult.data?.resultContent ? this.parseRelatedConcepts(relatedResult.data?.resultContent) : [];
        this.loadoing2 = false
      } catch (error) {
        this.$message.error('查询失败，请重试');
        console.error('AI查询错误:', error);
      }
    },

    /**
     * 调用后端askai接口
     * @param {string} prompt - 完整的提示词
     */
    async callAskAiApi(prompt) {
      const response = await fetch('http://localhost:9001/api/askai', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ prompt })
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      return response.json();
    },

    /**
     * 解析相关概念结果
     * @param {string} data - API返回的相关概念文本
     */
    parseRelatedConcepts(data) {
      // 简单解析，假设返回格式为数字加点开头的列表
      return data.split('\n')
        .filter(line => line.trim() && line.match(/^\d+\./))
        .map(line => line.replace(/^\d+\.\s*/, ''))
        .slice(0, 5); // 确保只取前5条
    },



    /**
     * 搜索相关笔记
     */
    async searchRelatedNotes() {
      if (!this.inputText.trim()) {
        this.relatedConceptsInNote = [];
        return;
      }

      try {
        this.loadoing6 = true;

        // 调用后端API搜索相关笔记
        const response = await fetch(`http://localhost:9001/api/knowledge/searchRelated?query=${encodeURIComponent(this.inputText.trim())}`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          }
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const result = await response.json();

        if (result.success) {
          this.relatedConceptsInNote = result.data || [];
        } else {
          console.error('搜索相关笔记失败:', result.message);
          this.relatedConceptsInNote = [];
        }
      } catch (error) {
        console.error('搜索相关笔记错误:', error);
        this.relatedConceptsInNote = [];
      } finally {
        this.loadoing6 = false;
      }
    },

    /**
     * 处理加入笔记按钮点击事件
     */
    async handleAddToNotes() {
      if (!this.conceptExplanation || !this.inputText.trim()) {
        this.$message.warning('请先进行AI查询获取结果');
        return;
      }

      try {
        this.loadoing3 = true;

        // 构建笔记内容
        const content = `${this.conceptExplanation}\n\n---\n\n相关概念：\n${this.relatedConcepts.map((concept, index) => `${index + 1}. ${concept}`).join('\n')}`;

        // 调用后端API创建知识库
        const response = await fetch('http://localhost:9001/api/knowledge/create', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            name: this.inputText.trim(),
            content: content
          })
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const result = await response.json();

        if (result.success) {
          this.$message.success('笔记添加成功！');
          // 重新搜索相关笔记
          await this.searchRelatedNotes();
        } else {
          this.$message.error(result.message || '添加笔记失败');
        }
      } catch (error) {
        this.$message.error('添加笔记失败，请重试');
        console.error('添加笔记错误:', error);
      } finally {
        this.loadoing3 = false;
      }
    }
  }
};
</script>

<style scoped>
.ask-ai-popup {
  width: 100%;
  padding: 15px;
}

.card-header {
  text-align: center;
}

.input-field {
  margin-bottom: 15px;
}

.query-button {
  width: 100%;
  margin-bottom: 10px;
}

.note-button {
  width: 100%;
  margin-bottom: 20px;
}

.result-section {
  margin-bottom: 20px;
}

.result-section h4 {
  font-size: 16px;
  margin-bottom: 10px;
  color: #333;
}

.result-card {
  background-color: #f9f9f9;
  border: 1px solid #eee;
}

.empty-result {
  color: #999;
  text-align: center;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.related-concepts-list {
  padding-left: 20px;
}

.related-concepts-list li {
  margin-bottom: 8px;
  line-height: 1.5;
}
</style>